#!/usr/bin/env python
#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
'''find_peer_lists.py -- find lists of peers in ClearView logs.'''

import bulk_inserter
import log_parser
from pydht.vuze import is_peer_record

import psycopg2

import sys


class LogProcessor(object):
  def __init__(self, conn, table_name):
    query = 'INSERT INTO %s (dhtkey, peer, port) VALUES' % table_name
    self.inserter = bulk_inserter.BulkInserter(conn, query, 3)

  def process_record(self, key, time, version, originator, value):
    if len(value) <= 5 and value.isdigit():
      port = value
    else:
      port = is_peer_record(value)
    if port is not None:
      self.inserter.insert((psycopg2.Binary(key), originator[0], port))

  def done(self):
    self.inserter.done()

def main(argv):
  conn = psycopg2.connect('dbname=dhtsearch')


  lp = LogProcessor(conn)

  for log in argv[1:]:
    lst = log_parser.get_stores(log, True)
    for (key, time, version, originator, value) in lst:
      lp.process_record(key, time, version, originator, value)

  lp.done()

  conn.commit()
  conn.close()

from cypeer_lists_proc import LogProcessor
if __name__ == '__main__':
  main(sys.argv)
